package com.example.demo.wx.serve;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.wx.model.TextMessage;
import com.example.demo.wx.model.WxText;
import com.example.demo.wx.serve.imp.WeiXinService;
import com.example.demo.wx.util.WeChatUtil;
import com.example.demo.wx.util.WxSendConfig;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Map;

/**
 * TODO
 *
 * @author liuningning
 * @date 2023/10/30 14:08
 */
@Slf4j
@Service
public class WeiXinServiceImp implements WeiXinService {

    private static String sendMessage_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}";

    private static String corpId = "wwc317d82aae5a7cd3";
    private static String coprsecret = "e9QoXO2X0ClRWeCHCqiBUPdmRbZ4qm4R2Hx7iq1Wl3A";
    private static Integer agentId = 1000002;

    @Override
    public String sendSimpleText(String[] toArr, String content) {
        if (ArrayUtils.isEmpty(toArr)){
            return null;
        }
        // 1. 获取 token
        String accessToken = getWeiXinToken();
        // 2 构建普通文本对象
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        TextMessage message = new TextMessage();
        // 1.1非必需
        // 不区分大小写
        message.setTouser(StringUtils.join(toArr,"|"));
        // 1.2必需
        message.setMsgtype("text");
        message.setAgentid(agentId);
        WxText wxText = new WxText();
        wxText.setContent(content);
        message.setText(wxText);
        String jsonMessage = gson.toJson(message);
        // 3. 发送 json 形式的获取，获取响应信息
        return messageResponse(accessToken, jsonMessage);
    }
    public String getWeiXinToken() {
        return WeChatUtil.getAccessToken(corpId, coprsecret).getToken();
    }

    public String messageResponse(String accessToken, String jsonMessage) {
        String url = MessageFormat.format(sendMessage_url, accessToken);
        // 4.调用接口，发送消息
        JSONObject jsonObject = WeChatUtil.httpRequest(url, "POST", jsonMessage);
        // 4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInteger("errcode")) {
                log.info("消息发送失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"),
                        jsonObject.getString("errmsg"));
            }
        }
        return jsonObject.toString();
    }

    @Override
    public String sendVelocityText(String title, String[] toArr, Map<String, Object> dataMap, String templateName) {
        return null;
    }
}
